<template>
  <div ref="container" class="figure-container" @click="rotateMode"></div>
</template> 

<script>
import * as THREE from 'three';
import { onMounted, ref } from 'vue';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js';
export default {
  name: 'MultiTextureFigure',
  setup() {
    // 射线投射器
    const raycaster = new THREE.Raycaster();
    // 鼠标位置
    const mouse = new THREE.Vector2();
    const gui = new GUI();
    const container = ref(null);
    let scene, camera, renderer;
    let mouseX = 0;
    let mouseY = 0;
    let leftEye; //眼睛左
    let rightEye; //眼睛右
    let leftPupil; //瞳孔
    let rightPupil; //瞳孔
    let blinkInterval; // 用于存储眨眼动画的定时器
    let windowHalfX = window.innerWidth / 2;
    let windowHalfY = window.innerHeight / 2;
    let headMesh;
    const textureLoader = new THREE.TextureLoader();
    // 旋转动画相关变量
    let isRotating = false;
    let targetRotation = 0;
    let currentRotation = 0;
    const rotationSpeed = 0.12; // 旋转速度

    //初始化
    const init = () => {
      // 创建场景
      scene = new THREE.Scene();

      // 创建相机 视角,宽高比,最近平面,最远平面
      camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.1, 1000);
      camera.position.z = 6;

      // 创建渲染器
      renderer = new THREE.WebGLRenderer({ alpha: true });
      renderer.setSize(window.innerWidth, window.innerHeight);
      container.value.appendChild(renderer.domElement);

      // 加载多张图片纹理

      const headTexture = textureLoader.load('https://static.jiyi.show/free/role/matcap.png');

      //   // 创建几何体
      const headGeometry = new THREE.SphereGeometry(2, 32, 32);
      //   const headGeometry1 = new THREE.PlaneGeometry(1, 1);
      // 创建材质
      const headMaterial = new THREE.MeshBasicMaterial({ map: headTexture ,transparent:true});
      // 创建网格
      headMesh = new THREE.Mesh(headGeometry, headMaterial);
      // 设置网格位置
      headMesh.position.set(0, 0, 0); // 头部在身体上方
      // 将网格添加到场景
      scene.add(headMesh);
      initChild();
      // 添加窗口大小调整事件监听器
      window.addEventListener('resize', onWindowResize, false);

      // 开始动画循环
      document.addEventListener('mousemove', onDocumentMouseMove, false);

      function onDocumentMouseMove(event) {
        mouseX = event.clientX - windowHalfX;
        mouseY = event.clientY - windowHalfY;
      }
      function onDocumentMouseClick(event) {
        // 将鼠标位置转换为归一化设备坐标（NDC）
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // 更新射线投射器
        raycaster.setFromCamera(mouse, camera);

        // 射线与模型的交点
        const intersects = raycaster.intersectObjects([headMesh]);

        if (intersects.length > 0) {
          // 点击到模型，开始旋转
          isRotating = true;
          targetRotation = currentRotation + Math.PI * 2;
        }
      }
      document.addEventListener('click', onDocumentMouseClick, false);
      // 启动眨眼动画
      startBlinking();
      animate();
      function animate() {
        requestAnimationFrame(animate);

        // 在这里可以添加动画逻辑
        // 例如：形象旋转
        //   scene.rotation.y += 0.01;
        // 平滑更新相机旋转
        const rotationFactor = 0.0004;
        const rotationX = mouseY * rotationFactor;
        const rotationY = mouseX * rotationFactor;

        // 更新模型旋转

        if (isRotating) {
          // 计算本次旋转的增量
          const deltaRotation = Math.min(rotationSpeed, targetRotation - currentRotation);
          currentRotation += deltaRotation;
          headMesh.rotation.y += deltaRotation;

          if (currentRotation >= targetRotation) {
            // 旋转完成
            isRotating = false;
            currentRotation = targetRotation % (Math.PI * 2);
          }
        } else {
          if (headMesh) {
            headMesh.rotation.x = rotationX;
            headMesh.rotation.y = rotationY;
          }
        }
        // 渲染场景
        renderer.render(scene, camera);
      }
    };
    const initChild = () => {
      const mtlLoader = new MTLLoader();
      // 加载 .mtl 文件
      mtlLoader.load(
        'public/models/test1.mtl',
        (materials) => {
          // 预加载材质
          materials.preload();

          // 创建 OBJLoader 实例
          const objLoader = new OBJLoader();
          // 设置材质
          objLoader.setMaterials(materials);
          // 加载 .obj 文件
          objLoader.load(
            'public/models/test2.obj',
            (object) => {
              // 将模型放置到盒子中心

              // 将模型添加到场景 
              // console.log(object,115441545)
              scene.add(object.children[0]);
            },
            (xhr) => {
              // 加载进度
              console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
            },
            (error) => {
              // 加载错误处理
              console.log('An error happened: ' + error);
            },
          );
        },
        (xhr) => {
          // .mtl 文件加载进度
          console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
        },
        (error) => {
          // .mtl 文件加载错误处理
          console.log('An error happened: ' + error);
        },
      );
      // let folder=gui.addFolder('立方体位置')
      // folder.add(headMesh.position, 'x', -5, 5).name('调整精灵x轴左右方位');
      // folder.add(headMesh.position, 'y', -5, 5).name('调整精灵y轴左右方位');
      // folder.add(headMesh.position, 'z', -5, 5).name('调整精灵z轴左右方位');
      // 眼睛（球体）
      const bodyTexture = textureLoader.load('https://static.jiyi.show/free/role/bakedHead.png');
      bodyTexture.offset.set(0.1, 0.25); // 从图片的 (0.2, 0.2) 位置开始
      bodyTexture.repeat.set(0.1, 0.1); // 使用图片的 0.6x0.6 区域

      const eyeGeometry = new THREE.SphereGeometry(0.2, 32, 32);
      const eyeMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });

      leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
      leftEye.position.set(-0.6, 0.5, 1.8);
      headMesh.add(leftEye);

      rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
      rightEye.position.set(0.6, 0.5, 1.8);
      headMesh.add(rightEye);
      // 创建眉毛的几何体（使用 BoxGeometry 模拟眉毛）
      const eyebrowMaterial = new THREE.MeshBasicMaterial({ color: 0x000000 });
      const eyebrowGeometry = new THREE.BoxGeometry(1, 0.1, 0.1);

      // 左眉毛
      const leftEyebrow = new THREE.Mesh(eyebrowGeometry, eyebrowMaterial);
      leftEyebrow.position.set(-1, 0.7, 0);
      headMesh.add(leftEyebrow);

      // 右眉毛
      const rightEyebrow = new THREE.Mesh(eyebrowGeometry, eyebrowMaterial);
      rightEyebrow.position.set(1, 0.7, 0);
      headMesh.add(rightEyebrow);

      // 瞳孔（球体）
      const pupilGeometry = new THREE.SphereGeometry(0.08, 32, 32);
      const pupilMaterial = new THREE.MeshPhongMaterial({ color: 0x000000 });

      leftPupil = new THREE.Mesh(pupilGeometry, pupilMaterial);
      leftPupil.position.set(-0.6, 0.5, 2);
      headMesh.add(leftPupil);

      rightPupil = new THREE.Mesh(pupilGeometry, pupilMaterial);
      rightPupil.position.set(0.6, 0.5, 2);
      headMesh.add(rightPupil);

      // 嘴巴（圆环）
      const mouthGeometry = new THREE.TorusGeometry(0.5, 0.1, 16, 32);
      const mouthMaterial = new THREE.MeshPhongMaterial({ color: 0xff6666 });
      const mouth = new THREE.Mesh(mouthGeometry, mouthMaterial);
      mouth.position.set(0, -0.5, 1.5);
      mouth.rotation.x = Math.PI / 2;
      headMesh.add(mouth);
      // 帽子（缩小尺寸并调整位置）
      const hatMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000 });

      // 帽檐（半径从 2.5 改为 1.2）
      const brimGeometry = new THREE.CylinderGeometry(1.2, 1.2, 0.15, 32);
      const brim = new THREE.Mesh(brimGeometry, hatMaterial);
      brim.position.set(0, 1.8, 0); // 降低高度适应头部
      headMesh.add(brim);

      // 帽顶（半径从 1.5 改为 0.8，高度从 3 改为 2）
      const topGeometry = new THREE.CylinderGeometry(0.8, 0.8, 0.8, 32);
      const top = new THREE.Mesh(topGeometry, hatMaterial);
      top.position.set(0, 2, 0); // 降低高度
      headMesh.add(top);

      // 头发（圆柱体）
      // const hairGeometry = new THREE.CylinderGeometry(0.2, 0.2, 1, 16);
      // const hairMaterial = new THREE.MeshPhongMaterial({ color: 0x663300 });

      // const hair1 = new THREE.Mesh(hairGeometry, hairMaterial);
      // hair1.position.set(-0.8, 2, 0);
      // hair1.rotation.z = Math.PI / 4;
      // headMesh.add(hair1);

      // const hair2 = new THREE.Mesh(hairGeometry, hairMaterial);
      // hair2.position.set(0, 2.2, 0);
      // headMesh.add(hair2);

      // const hair3 = new THREE.Mesh(hairGeometry, hairMaterial);
      // hair3.position.set(0.8, 2, 0);
      // hair3.rotation.z = -Math.PI / 4;
      // headMesh.add(hair3);
      // 耳朵（半球体）
      const earGeometry = new THREE.SphereGeometry(0.5, 32, 32, 0, Math.PI * 2, 0, Math.PI / 2); // 半球体
      const earMaterial = new THREE.MeshPhongMaterial({ color: 0xffcc99 });

      const leftEar = new THREE.Mesh(earGeometry, earMaterial);
      leftEar.position.set(-1.8, 0.5, 0);
      leftEar.rotation.z = Math.PI / 2.4; // 旋转耳朵使其朝向侧面
      headMesh.add(leftEar);

      const rightEar = new THREE.Mesh(earGeometry, earMaterial);
      rightEar.position.set(1.8, 0.5, 0);
      rightEar.rotation.z = -Math.PI / 2.4; // 旋转耳朵使其朝向侧面
      headMesh.add(rightEar);
    };
    const onWindowResize = () => {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    };

    const startBlinking = () => {
      blinkInterval = setInterval(() => {
        blinkEyes();
      }, 5000); // 每 5 秒眨眼一次
    };
    const blinkEyes = () => {
      // 缩小眼睛（模拟眨眼）
      leftEye.scale.y = 0.1;
      rightEye.scale.y = 0.1;
      leftPupil.scale.y = 0.1;
      rightPupil.scale.y = 0.1;
      // 0.2 秒后恢复眼睛大小
      setTimeout(() => {
        leftEye.scale.y = 1;
        rightEye.scale.y = 1;
        leftPupil.scale.y = 1;
        rightPupil.scale.y = 1;
      }, 200);
    };
    onMounted(() => {
      init();
    });

    return {
      container,
      headMesh,
    };
  },
};
</script>

<style scoped lang="less">
.figure-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 999999;
}
</style>

